import React, { FC, useContext, useEffect, useState } from 'react'
import { getNoteDetail, getVipNoteList, noteRec } from "../../api";
import { Empty, Button, Cell, Space, Toast, Notify, Card, Swiper, Dialog, Loading } from "react-vant";
import { Qr, Like } from '@react-vant/icons'
import girl from "../../assets/girl.svg"
import boy from "../../assets/boy.svg"
import nodata from "../../assets/nodata.svg"
import { useNavigate } from "react-router-dom";
import { copy, wxPay } from '../../utils/utils';
import { DotLoading, Image, ImageViewer, InfiniteScroll, Skeleton, Tag } from "antd-mobile";
import { appStoreContext } from '../../App'

type Item = {
    _id: string,
    pushUserId: string,
    imageUrls: string[],
    imageIds: { url: string }[],
    account: string,
    accountType: string,
    content: string,
    createTs: string,
    pullTs: string,
    sex: string,
    age: number,
    tags: string[],
    wxQrCode: string,
    show?: Boolean,
    province: string,
    city: string,
    rectangle: string,
    recommend: string
}
type ListProps = Item[]


const CellItem = (props: { data: Item }) => {
    let { data } = props

    let appStore = useContext(appStoreContext)

    const navigate = useNavigate()

    const getNoteDetailById = async (noteId: string) => {
        let { data } = await getNoteDetail({ noteId })
        console.log(data);
        // 3卡次不够 需要购买
        if (data?.needPay) {
            Dialog.confirm({
                title: '提示',
                message: '您的卡次不足，需要消耗3次卡，是否直接支付？',
                confirmButtonText: '直接支付3元',
                cancelButtonText: '购买次卡',
            }).then(() => {
                wxPay({orderType: 'count', pullkey: 'C3'},() => {getNoteDetailById(noteId)})
            }).catch(() => {
                // on cancel
                navigate('/my')
            });
        }else{
            if (data.wxQrCode){
                ImageViewer.show({
                    image: data.wxQrCode,
                    renderFooter: () => {
                        return (
                            <div className='text-center pb10'>
                                <Tag color='default' className='px10 py7' round>长按二维码可直接添加</Tag>
                            </div>
                        )
                    }
                })
            }else{
                copy(data.account);
                Toast('账号复制成功');
            }
        }
    }
    
    return (
        <div className='p8'>
            <Card round>
                <Card.Cover onClick={() => {
                    let images: string[] = []
                    if (data.imageIds.length > 0) {
                        images = data.imageIds.map((item) => {
                            return item.url
                        })
                    }
                    ImageViewer.Multi.show({
                        images                           
                    })

                }}>
                    <Swiper>
                        {data.imageIds.map((item, index) => {
                            return (
                                <Swiper.Item key={index} style={{ minHeight:200, maxHeight: 400 }}>
                                    <Image fit='contain' lazy placeholder={
                                            <Skeleton style={{
                                                '--width': '70%',
                                                '--height': '100%'
                                            }} animated />
                                    } src={item.url} />
                                </Swiper.Item>
                            )
                        })}
                    </Swiper>
                </Card.Cover>
                <Card.Header
                    extra={<Image src={data.sex == '0' ? boy : girl} />}
                    // onClick={() => Toast.info('点击了Header区域')}
                >
                    {data.province} {data.city} （{data.account}）
                </Card.Header>
                <Card.Body>
                    {data.tags.map((item, index) => {
                        return <Tag key={index} className='mr5 mb5' color="warning" round>{item}</Tag>
                    })}
                    <Tag className='mr5 mb5' color='#c08515' round>{data.accountType}</Tag>
                    <Tag className='mr5 mb5' color='#f3593a' round>{data.sex == '1' ? '女' : '男'}</Tag>
                    <Tag color="success" round>{data.age}岁</Tag>
                    <p className='text-c666 mt3'><span className='text-c999'>留言：</span>{data.content || '- -'}</p>
                </Card.Body>
                <Card.Footer>
                    <Space>
                        <Button round icon={<Qr />} size='small' color='linear-gradient(to right, #ff6034, #ee0a24)' onClick={() => {
                            getNoteDetailById(data._id)
                        }}>
                            {data.wxQrCode ? '微信二维码':'复制账号'}
                        </Button>
                        {/* <Button
                            icon={<Like />}
                            round
                            color='linear-gradient(to right, #ff6034, #ee0a24)'
                            size='small'
                            onClick={() => {
                                noteRec({ noteId: data._id }).then((res) => {
                                    Toast.success('推荐成功')
                                })
                            }}
                        >
                            推荐{data.recommend}
                        </Button> */}
                    </Space>
                </Card.Footer>
            </Card>
        </div>
    )
}


const My: FC = () => {

    const [pageNum, setPageNum] = useState(1)
    const [pageSize, setPageSize] = useState(10)

    const [myPullList, setMyPullList] = useState<ListProps>([]);

    const getVipNoteListHandle = async () => {
        let res = await getVipNoteList({ pageNum, pageSize });
        console.log(res);
        return res.data
    }

    const [hasMore, setHasMore] = useState(true)
    
    const loadMore = async () => {
        setPageNum(pageNum + 1)
        const appendList = await getVipNoteListHandle()
        setMyPullList(val => [...val, ...appendList])
        setHasMore(appendList.length > 0)
    }  
    

    return (
        <div className='pb15'>
            {myPullList.length > 0 ? myPullList.map((item: Item, index) => {
                return (
                    <CellItem key={item._id + index} data={item} />
                )
            }): <>
                <Skeleton.Title animated />
                <Skeleton.Paragraph lineCount={7} animated />
            </>}

            <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
                {hasMore ? (
                    <>
                    <span>一波数据正在赶来</span>
                    <DotLoading />
                    </>
                ) : '更多数据请开通VIP后再来查看'}
            </InfiniteScroll>
            
            {/* {myPullList.length > 0 && <div className='px15 mt10'>
                <Button
                    icon={<Like />}
                    round
                    block
                    color='linear-gradient(to right, #ff6034, #ee0a24)'
                    onClick={() => {
                        Dialog.confirm({
                            title: '开通会员',
                            message: 'res.msg',
                            confirmButtonText: '立刻开通',
                            cancelButtonText: '我再想想',
                        })
                            .then(() => {
                            })
                            .catch(() => {
                                console.log('catch');
                            })
                    }}
                >
                    查看更多
                </Button>
            </div>} */}
        </div>

    )
}

export default My;